package com.hzmg.akka.http;

import akka.actor.typed.ActorSystem;
import akka.actor.typed.javadsl.Behaviors;
import akka.http.javadsl.Http;
import akka.http.javadsl.ServerBinding;
import akka.http.javadsl.ServerBuilder;
import akka.http.javadsl.server.AllDirectives;
import akka.http.javadsl.server.Route;
import cn.hutool.core.lang.Console;
import com.hzmg.akka.utils.NetUtils;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletionStage;

@Component
public class AkkaHttpDemo extends AllDirectives {
    static AkkaHttpDemo akkaHttpDemo = new AkkaHttpDemo();

    public static void main(String[] args) throws Exception {
        akkaHttpDemo.startHttpServer();
    }

    private void startHttpServer() {
        //server-bootstrap boot up server using the route as defined below
        ActorSystem<Void> system = ActorSystem.create(Behaviors.empty(), "firstHttpServer");
        final Http http = Http.get(system);
        //In order to access all directives we need an instance where the routes are define.

        final ServerBuilder serverBuilder=
                http.newServerAt(NetUtils.getLocalHost(), 8081);
        //serverBuilder.bind(createRoute());
        serverBuilder.bind(createRoute2());
        /*binding
                //trigger unbinding from the port
                .thenCompose(ServerBinding::unbind)
                //and shutdown when done
                .thenAccept(unbound -> system.terminate());*/
        Console.log("Server online at http://{}:8081", NetUtils.getLocalHost());
    }

    private Route createRoute() {
        return concat(
                path("hello", () ->
                        get(() ->
                                complete("<h1>hello akka-http-demo</h1>")))
        );
    }
    private Route createRoute2() {
        return concat(
                path("hello2", () ->
                        get(() ->
                                complete("<h1>hello2 akka-http-demo</h1>")))
        );
    }
}
